<?php
namespace api\modules\mp\controllers;

use yii\base\Security;
use yii\helpers\StringHelper;
use yii\web\Controller;
use Yii;
use yii\web\Response;

class UserController extends Controller {
    public $enableCsrfValidation = false;

    public function beforeAction($action) {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return parent::beforeAction($action);
    }

    public function behaviors() {
        return array_merge(parent::behaviors(), [
            [
                'class' => 'yii\filters\auth\QueryParamAuth',
                'tokenParam' => 'session',
                'optional' => ['login']
            ],
        ]);
    }


    public function actionIndex() {
        echo __METHOD__;
    }

    /**
     * 前端小程序，首先调用微信端checkSession，fail时调用此login接口，执行登录 更新微信的session_key并存储
     * @return array
     */
    public function actionLogin() {
        $code = Yii::$app->request->post('code');
        //todo wx login
        $session_key = 'zxcivj';//todo update auth_wechat表
        $openid = 'asidljflsifjsdalfjisdf';
        $one = Yii::$app->db->createCommand("SELECT * FROM auth_wechat WHERE mp_openid='$openid'")->queryOne();
        if ($one) {
            Yii::$app->db->createCommand()->update('auth_wechat', ['mp_session_key' => $session_key], "mp_openid='$openid'")->execute();
        } else {
            Yii::$app->db->createCommand("INSERT INTO auth_wechat (mp_openid,mp_session_key) VALUES ('$openid','$session_key')")->execute();
        }
        $validationKey = Yii::$app->request->cookieValidationKey ?: '';
        $value = Yii::$app->getSecurity()->hashData($openid, $validationKey);
        //var_dump($value);exit;
        //Yii::$app->request->enableCookieValidation
        return [
            'code' => 200,
            'data' => [
                'session' => $value,
            ]
        ];
    }

}
